﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Public.Ocean.Petrel.Extensions.UI
{
    public partial class DialogWrapperControl : UserControl
    {
        Action applyAction;

        public DialogWrapperControl()
        {
            InitializeComponent();
        }

        public DialogWrapperControl(Control content, Action applyAction)
        {
            InitializeComponent();
            content.Dock = DockStyle.Fill;
            Controls.Add(content);
            this.applyAction = applyAction;
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            ConnectToHost();
        }

        private void ConnectToHost()
        {
            Form form = FindForm();
            if (form != null)
            {
                form.AcceptButton = buttonOk;
                form.CancelButton = buttonCancel;
            }
        }

        private void buttonApply_Click(object sender, EventArgs e)
        {
            Apply();
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            buttonApply_Click(sender, e);
            Close(DialogResult.OK);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close(DialogResult.Cancel);
        }

        private void Apply()
        {
            if (applyAction != null)
            {
                applyAction();
            }
        }

        private void Close(DialogResult result)
        {
            Form form = FindForm();
            if (form != null)
            {
                form.DialogResult = result;
                form.Close();
            }
        }

        public static Control Wrap(Control content, Action apply)
        {
            DialogWrapperControl result = new DialogWrapperControl(content, apply);
            return result;
        }
    }
}
